package com.pearl.study.client.demo.lua;

import io.lettuce.core.ScriptOutputType;
import io.lettuce.core.api.sync.RedisCommands;
import org.redisson.api.RLock;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * @author TD
 * @version 1.0
 * @date 2024/7/25
 */
public class RedisLockUtils {


    /**
     * 尝试获取锁
     *
     * @param sync   连接
     * @param key    锁的 Key
     * @param value  锁的值
     * @param second 过期时间
     * @return 是否获取到锁
     * @throws IOException
     */

    public static boolean tryLock(RedisCommands<String, String> sync, String key, String value, String second) throws IOException {
        byte[] lua = RedisLockUtils.getResourceAsByteArray("tryLock.lua"); // 获取脚本流
        return sync.eval(lua, ScriptOutputType.BOOLEAN, new String[]{key}, value, second);      // 执行脚本
    }


    /**
     * 删除锁
     *
     * @param sync 连接
     * @param key  锁的 Key
     * @return 是否获取到锁
     * @throws IOException
     */

    public static void unlock(RedisCommands<String, String> sync, String key) throws IOException {
        byte[] lua = RedisLockUtils.getResourceAsByteArray("unlock.lua");
        boolean eval = sync.eval(lua, ScriptOutputType.BOOLEAN, new String[]{key});
    }


    public static byte[] getResourceAsByteArray(String resourceName) throws IOException {
        // 使用ClassLoader获取资源作为输入流
        try (InputStream inputStream = LuaLimitTest.class.getClassLoader().getResourceAsStream(resourceName)) {
            if (inputStream == null) {
                return null;
            }
            // 将输入流转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            return outputStream.toByteArray();
        }
    }
}
